//
//  M3U8Handle.m
//  LocalHttpServerExample
//
//  Created by Lin Eidan on 13-9-6.
//  Copyright (c) 2013年 taomee. All rights reserved.
//

#import "M3U8Handle.h"
#import "M3U8DownloadConfig.h"
#import "Common.h"
#import "config.h"
#import "VideoObj.h"
#import "Header.h"


@implementation M3U8Handle

-(id)initWithDownloadObj:(VideoObj *)obj{
    self = [super init];
    if (self) {
        self.contentId=obj.contentId;
        self.curNum=obj.currentPlayIndex;
        self.episodeId=obj.episodeId;
        self.totalDur=0;
        self.VideoObj = obj;
    }
    return self;
}

//cartoon
-(void)parseURLArray:(NSArray *)urlArray{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//	 		
//        });
//    });
    
    NSString* segmentPrefix = [self getSegmentPrefix];
    self.segmentsArray=[[NSMutableArray alloc] init];
    self.cartoonPicInLocalServerURLArray = [[NSMutableArray alloc] init];
    self.totalDur = urlArray.count;
    
    for (int i=0; i < urlArray.count; i++) {
        NSString *url = [urlArray objectAtIndex:i];
        M3U8SegmentInfo *segmentInfo=[[M3U8SegmentInfo alloc] initWithLength:1.0 andURL:url];
        [self.segmentsArray addObject:segmentInfo];
        
        NSString* localFileName = [NSString stringWithFormat:@"%@%d",kSegmentIdFlag,i];
        NSString* localURL = [segmentPrefix stringByAppendingString:localFileName];
        [self.cartoonPicInLocalServerURLArray addObject:localURL];
    }
    
    if ([self.delegate respondsToSelector:@selector(m3U8HandleSuccessed:andIsCartoon:andVideoObj:)]) {
        [self.delegate m3U8HandleSuccessed:self andIsCartoon:YES andVideoObj:self.VideoObj];
    }

   
}


-(void)parseURL:(NSString *)url{
    self.url=url;
    
    if (isiOS7) {
        
        NSString *downloadPath= [[DownloadVideoManager sharedInstance] getEpisodeFilePathWithContentId:self.VideoObj.contentId andEpisodeId:self.VideoObj.episodeId andNeedCreateFolder:YES];
        NSString *fileName = [[NSString alloc] initWithFormat:@"%@_%@.temp",self.VideoObj.contentId,self.VideoObj.episodeId];

        [[DownloadGetData sharedInstance] startTaskBackgroundDataGet:url andFileFolderPath:downloadPath andFileName:fileName andResultIsJSON:NO andTaskCompletion:^(NSURLResponse *response, id responseObj, BOOL isSuccess) {
            if (isSuccess) {
                [self getDataSuccess:responseObj];
            }else{
                [self getDataFailed];
            }
        }];
        
//        [[DownloadGetData sharedInstance] startGet:url andResultIsJSON:NO andTaskCompletion:^(NSURLSessionDataTask *task, id responseObj, BOOL isSuccess) {
//            if (isSuccess) {
//                [self getDataSuccess:responseObj];
//            }else{
//                [self getDataFailed];
//            }
//        }];
        
    }else{
        [[DownloadGetData sharedInstance] startGet:url andResultIsJSON:NO andCompletion:^(AFHTTPRequestOperation *operation, id responseObj, BOOL isSuccess) {
            if (isSuccess) {
                [self getDataSuccess:responseObj];
            }else{
                [self getDataFailed];
            }
        }];
    }
    
}

-(void)m3u8HandleHasFailed{
    if ([self.delegate respondsToSelector:@selector(m3U8HandleFailed:andVideoObj:)]) {
        [self.delegate m3U8HandleFailed:self andVideoObj:self.VideoObj];
    }
}

-(NSString *)getSegmentPrefix{
    
    //m3u8文件要存储的文件夹，也是视频片段和漫画图片要存的文件夹。
    self.localM3U8FileFolder = [[DownloadVideoManager sharedInstance] getEpisodeFilePathWithContentId:self.contentId andEpisodeId:self.episodeId andNeedCreateFolder:YES];
    NSString* segmentPrefix = [[DownloadVideoManager sharedInstance] getLocalServerRequestFolderPathWithContentId:self.contentId andEpisodeId:self.episodeId]; //获得服务器地址。
    
    return segmentPrefix;
}

-(void)getDataSuccess:(NSData *)resultData{
    
    NSData *getData=resultData;
    
    NSStringEncoding encoding = 1;
    
    NSString *data=[[NSString alloc] initWithData:getData encoding:encoding];
    
    if (data == nil) {
        [self m3u8HandleHasFailed];
        return;
    }
    //重新创建本地m3u8文件
    
    NSString* segmentPrefix = [self getSegmentPrefix];
    NSMutableString *readyWriteToLocalData=[NSMutableString stringWithString:data];  //准备要写入的内容，准备改。
    
    //解析网络m3u8文件
    self.segmentsArray=[[NSMutableArray alloc] init];
    NSString *remainData=data;
   
    NSRange segmentRange = [remainData rangeOfString:@"#EXTINF:"];
    int index=0;
    NSString *baseURL=self.url;
    
    if (segmentRange.location == NSNotFound) {
        [self m3u8HandleHasFailed];
        return;
    }
    
    while (segmentRange.location != NSNotFound)
    {
        remainData = [remainData substringFromIndex:(segmentRange.location+ segmentRange.length)];
        // 读取片段时长
        NSRange commaRange = [remainData rangeOfString:@"\n"];
        NSString* value;
        if (commaRange.location != NSNotFound) {  //找到回车
            value= [remainData substringWithRange:NSMakeRange(0, commaRange.location)];
            NSRange temp = [value rangeOfString:@","];
            if (temp.location != NSNotFound ) {
                value = [value substringToIndex:temp.location];
            }
            remainData = [remainData substringFromIndex:commaRange.location];
        }else{  //没有找到回车
            [self m3u8HandleHasFailed];
            return;
        }
        
        // 读取片段url,下载用
        NSRange linkRangeBegin = [remainData rangeOfString:@"http"];
        NSRange linkRangeEnd = [remainData rangeOfString:@"#"];
        NSString *linkurl;
        NSString *trueLinkURL;
        if (linkRangeBegin.location !=NSNotFound) {  //绝对地址
            linkurl = [remainData substringWithRange:NSMakeRange(linkRangeBegin.location, linkRangeEnd.location - linkRangeBegin.location)];
            if (IsNull(linkurl) || linkurl.length == 0) {
                [self m3u8HandleHasFailed];
                return;
            }
            trueLinkURL=linkurl;
        }else{
            linkRangeBegin=[remainData rangeOfString:@"/"];
            if (linkRangeBegin.location != NSNotFound) {  //从根目录开始的相对地址。。
                linkurl = [remainData substringWithRange:NSMakeRange(linkRangeBegin.location, linkRangeEnd.location - linkRangeBegin.location)];
                if (IsNull(linkurl) || linkurl.length == 0) {
                    [self m3u8HandleHasFailed];
                    return;
                }
                if ([baseURL isEqualToString:self.url]) {
                    NSRange tempRange=[self.url rangeOfString:@"http://"];
                    baseURL=[self.url substringFromIndex:tempRange.location+tempRange.length];
                    tempRange = [baseURL rangeOfString:@"/"];
                    baseURL=[baseURL substringToIndex:tempRange.location];
                    baseURL=[NSString stringWithFormat:@"http://%@",baseURL];
//                    NSLog(@"%@",baseURL);
                }
            }else{   // //从当前目录开始的相对地址
                linkurl = [remainData substringWithRange:NSMakeRange(1, linkRangeEnd.location-1)];
                linkurl = [Common removeCharacterSpaceAndEnter:linkurl];
                
                if ([baseURL isEqualToString:self.url]) {
                    baseURL= [Common getFolderOfTheFile:self.url];
                }
            }
            
            if (IsNull(linkurl) || linkurl.length == 0 || IsNull(baseURL) || baseURL.length == 0) {
                [self m3u8HandleHasFailed];
                return;
            }
            trueLinkURL=[NSString stringWithFormat:@"%@/%@",baseURL,linkurl];
        }
        
        //还要处理逗号
        NSRange lastRange=[trueLinkURL rangeOfString:@","];
        if (lastRange.location != NSNotFound) {
            trueLinkURL=[trueLinkURL substringToIndex:lastRange.location];
        }
        //enter and space
        trueLinkURL=[Common removeCharacterSpaceAndEnter:trueLinkURL];
        
        if (IsNull(trueLinkURL) || trueLinkURL.length == 0 || IsNull(value) || value.length == 0) {
            [self m3u8HandleHasFailed];
            return;
        }
        
        M3U8SegmentInfo *segmentInfo=[[M3U8SegmentInfo alloc] initWithLength:[value floatValue] andURL:trueLinkURL];
        [self.segmentsArray addObject:segmentInfo];
        
        //替换URL
        NSString* localFileName = [NSString stringWithFormat:@"%@%d",kSegmentIdFlag,index];
        NSString* localURL = [segmentPrefix stringByAppendingString:localFileName];
        NSRange linkURLRange=[readyWriteToLocalData rangeOfString:linkurl];  //片段本地地址
        [readyWriteToLocalData  replaceCharactersInRange:linkURLRange withString:[NSString stringWithFormat:@"%@\n",localURL]];
        
        remainData = [remainData substringFromIndex:linkRangeEnd.location];
        segmentRange = [remainData rangeOfString:@"#EXTINF:"];
        
        self.totalDur+=value.floatValue;
        index++;
    }
    //写入本地
    NSMutableData *writer = [[NSMutableData alloc] init];
    [writer appendData:[readyWriteToLocalData dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *localM3U8FilePath=[self.localM3U8FileFolder stringByAppendingPathComponent:kLocalM3U8FileName];  //m3u8地址
    self.localHttpServerM3U8FilePath=[NSString stringWithFormat:@"%@%@",segmentPrefix,kLocalM3U8FileName];   //在服务器的地址
    
    BOOL bSucc =[writer writeToFile:localM3U8FilePath atomically:YES];
    
    if (bSucc) {
        if ([self.delegate respondsToSelector:@selector(m3U8HandleSuccessed:andIsCartoon:andVideoObj:)]) {
            [self.delegate m3U8HandleSuccessed:self andIsCartoon:NO andVideoObj:self.VideoObj];
        }
    }else{
        [self m3u8HandleHasFailed];
        return;
    }
}


-(void)getDataFailed{
    [self m3u8HandleHasFailed];
}


@end



@implementation M3U8SegmentInfo

-(id)initWithLength:(float )length andURL:(NSString *)url{
    self = [super init];
    if (self) {
        self.segmentLength=length;
        self.segmentURL=url;
    }
    return self;
}

@end
